<?php

class multitender_model_query_users extends multitender_model {

    public $lenlist=10;
    public $queries;
    private $sess;
    private $joom_id;

    function  __construct() {
        $this->queries = new multitender_model_list_queries();
        parent::__construct();
        $this->sess    = md5(session_id());
        $this->joom_id = $this->conf['user']['id'];
        $this->db      = & $this->conf['dbs']['person'];
    }

    public function get_user_id() {
        if (is_null($this->db)) {
            return false;
        }

        if (!$this->joom_id) {
            return $this->sess;
        }
        $sql="SELECT id FROM users WHERE joomla_id=".$this->joom_id;
        if ($id=$this->db->GetOne($sql)) {
            return $id;
        } else {
            return $this->add_user();
        }
    }

    private function add_user() {
        if (is_null($this->db)) {
            return false;
        }
        $sql="INSERT INTO users(joomla_id) VALUES('$this->joom_id')";
        if ($this->db->Execute($sql)) {
            return $this->db->Insert_ID();
        } else {
            return false;
        }
    }

    public function user_add_find($user_id, &$obj, $total) {
        if (is_null($this->db)) {
            return false;
        }

        if ($user_id) {
            $colname="user_id";
        } else {
            $colname="session_id";
            // FIXME Joomla использует свои сессии
            // FIXME не записывать ботов, они все равно не записывают сессии
            $user_id = 0; //crc_p(session_id());
        }

        $type_user   = $this->conf['user']['type'];
        $type_search = 'search';
        $s_id=$this->queries->get_query_id($obj, $total);        
        if (!$s_id) {
            exit;
        }

        // запись статистики
        DEFINE('MT_SEARCH_COUNT_KEY', 'MT_SEARCH_COUNT_KEY');
        DEFINE('MT_PAGENAV_COUNT_KEY', 'MT_PAGENAV_COUNT_KEY');
        DEFINE('TODB_EVERY', 100);
        $memcache = new Memcache();
        $memcache->connect('localhost', 11611, 15);

        $page = isset($_GET['page']) ? (int) $_GET['page'] : NULL;
        if ( $page < 2 ) {
            $search = $memcache->get(MT_SEARCH_COUNT_KEY);
            if ($search === FALSE) {
                $search = $this->db->GetOne("SELECT count FROM search_count WHERE type = 'search'");
                $memcache->set(MT_SEARCH_COUNT_KEY, $search);
            }
            if ($search % TODB_EVERY == 0) {
                $search++;
                $this->db->Execute("UPDATE search_count SET count=$search WHERE type = 'search'");    
            }
            $memcache->increment(MT_SEARCH_COUNT_KEY);
        } else {
            $pagenav = $memcache->get(MT_PAGENAV_COUNT_KEY);
            if ($pagenav === FALSE) {
                $pagenav = $this->db->GetOne("SELECT count FROM search_count WHERE type = 'pagenav'");
                $memcache->set(MT_PAGENAV_COUNT_KEY, $pagenav);
            }
            if ($pagenav % TODB_EVERY == 0) {
                $pagenav++;
                $this->db->Execute("UPDATE search_count SET count=$pagenav WHERE type = 'pagenav'");
            }
            $memcache->increment(MT_PAGENAV_COUNT_KEY);
        }
        $lsr = $this->conf['db_conf']['person']['last_searchs_replays'];

        $sql="SELECT search_id FROM last_search WHERE $colname=? ORDER BY id DESC LIMIT ?";
        $ls = $this->db->GetCol($sql, array($user_id, $lsr));
        $ins = true;
        if ( in_array($s_id, $ls) ) {
            $ins = false;
        }

        $timedb = $this->db->BindTimeStamp(time());

        if ($ins) {
            $sql="INSERT INTO last_search(search_id, $colname, type_user, type_search, date, time, mtime, mtime_mysql, mtime_sphinx) " .
                    " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $this->db->Execute($sql, array($s_id, $user_id, $type_user, $type_search, $timedb, $timedb, $obj->mtime, $obj->mtime_mysql, $obj->mtime_sphinx));
        }
        return $s_id;
    }

    public function get_last_query($user_id, $offset=0, $count=10) {
        if (is_null($this->db)) {
            return false;
        }

        if ($user_id) {
            $colname="user_id";
        } else {
            $colname="session_id";
            $sesid=session_id();
            sscanf(crc_p($sesid), '%u', $user_id);
        }

        $sql ="SELECT SQL_CALC_FOUND_ROWS search_id FROM last_search WHERE $colname = ?" .
                " ORDER BY id DESC LIMIT $offset, $count";

        $last_s = $this->db->GetCol($sql,array($user_id));

        if ($last_s) {
            $total = $this->db->GetArray("SELECT FOUND_ROWS()");
            $searchs=$this->queries->GetList($last_s);
            foreach ($last_s as &$id) {
                foreach ($searchs as $s) {
                    if ($id==$s['id']) {
                        $id = $s;
                    }
                }
            }
            $total = $total[0][0];
            $last_s['total']=$total;
            return $last_s;
        } else {
            return false;
        }
    }

    public function last_query($user_id) {
        if (is_null($this->db)) {
            return false;
        }
        $sql="SELECT search_id FROM last_search WHERE user_id=$user_id ORDER BY id DESC";
        $search_id=$this->db->GetOne($sql);
        if ($search_id) {
            return $search_id;
        } else {
            return false;
        }
    }

    public function get_all_query($offset, $count=10, $user='all', $find='all') {
        if (is_null($this->db)) {
            return false;
        }

        $sql ="SELECT SQL_CALC_FOUND_ROWS * FROM last_search ";

        $amp = "WHERE";
        $arr = array();
        if ($user != 'all') {
            $sql.=$amp." type_user=? ";
            $arr[] = $user;
            $amp = "AND";
        }

        if ($find != 'all') {
            $sql.=$amp." type_search=? ";
            $arr[] = $find;
        }
        $sql.="ORDER BY id DESC LIMIT ?,?";
        $arr[] = $offset;
        $arr[] = $count;

        if ($q = $this->db->GetAll($sql, $arr)) {
            $total = $this->db->GetArray("SELECT FOUND_ROWS()");
            $total = $total[0][0];
            $q['total']=$total;
            return $q;
        } else {
            return false;
        }
    }

    public function get_user_ids($ids) {

        if (is_null($this->db)) {
            return false;
        }

        $sql="SELECT * FROM users WHERE Id IN (".implode($ids,",").")";
        if ($us = $this->db->GetAll($sql)) {
            return $us;
        } else {
            return false;
        }
    }


}
